import {Component, OnInit} from '@angular/core';
import {UsedStorePService} from '../../../used-store/used-store-p.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {OperateService} from '../operate.service';
import {DatePipe} from '@angular/common';
import {NzModalService} from 'ng-zorro-antd/modal';

enum STATE {
  '待发放',
  '已发放',
  '已完成',
  '已失效',
}

enum TYPE {
  '实物' = 1,
  '虚拟-积分',
  '虚拟-礼包兑换码',
}

@Component({
  selector: 'app-exchange-records',
  templateUrl: './exchange-records.component.html',
  styleUrls: ['./exchange-records.component.scss']
})
export class ExchangeRecordsComponent implements OnInit {
  query = {
    user: '',
    orderNum: '',
    goodsType: '',
    state: '',
    time: '',
    grantTime: '',
    page: 1,
    pageSize: 10,
  };
  tableData = {
    checked: false,
    indeterminate: false,
    setOfCheckedId: new Set<number>(),
    total: 0,
    records: [],
  };
  expressModal = {
    visible: false,
    id: '',
    address: '',
    expressCode: '',
    expressNum: '',
  };
  STATE = STATE;
  logistics: any[] = [];
  TYPE = TYPE;

  constructor(
    private usedStorePService: UsedStorePService,
    private operateService: OperateService,
    private datePipe: DatePipe,
    private nzMessageService: NzMessageService,
    private nzModalService: NzModalService,
  ) {
  }

  ngOnInit(): void {
    this.usedStorePService.dictData('logistics_company').then((res: any) => {
      if (res.code === 0) {
        this.logistics = res.data.list.records;
      }
    });
    this.getExchangeRecordsList();
  }

  getExchangeRecordsList() {
    this.operateService.getExchangeRecordsList({
      user: this.query.user,
      orderNum: this.query.orderNum,
      goodsType: this.query.goodsType,
      state: this.query.state,
      beginTime: this.datePipe.transform(this.query.time[0], 'yyyy-MM-dd'),
      endTime: this.datePipe.transform(this.query.time[1], 'yyyy-MM-dd'),
      grantBeginTime: this.datePipe.transform(this.query.grantTime[0], 'yyyy-MM-dd'),
      grantEndTime: this.datePipe.transform(this.query.grantTime[1], 'yyyy-MM-dd'),
      page: this.query.page,
      pageSize: this.query.pageSize,
    }).then((res: any) => {
      if (res.code === 0) {
        this.tableData.records = res.data.records;
        this.tableData.total = res.data.total;
      }
    });
  }

  queryBtn() {
    this.query.page = 1;
    this.getExchangeRecordsList();
  }

  resetCondition() {
    this.query = {
      user: '',
      orderNum: '',
      goodsType: '',
      state: '',
      time: '',
      grantTime: '',
      page: 1,
      pageSize: 10,
    };
    this.getExchangeRecordsList();
  }

  onPageIndexChange(index: number) {
    this.query.page = index;
    this.getExchangeRecordsList();
  }

  onPageSizeChange(pageSize: number) {
    this.query.pageSize = pageSize;
    this.getExchangeRecordsList();
  }


  onAllCheckedWaitCheck(checked: boolean): void {
    this.tableData.records
      // // @ts-ignore
      // .filter(({disabled, status}) => !disabled && status !== 4)
      // @ts-ignore
      .forEach(({id}) => this.updateCheckedSetWaitCheck(id, checked));
    this.refreshCheckedStatusWaitCheck();
  }

  refreshCheckedStatusWaitCheck(): void {
    // @ts-ignore
    const listOfEnabledData = this.tableData.records;
    // @ts-ignore
    this.tableData.checked = listOfEnabledData.every(({id}) => this.tableData.setOfCheckedId.has(id));
    // @ts-ignore
    this.tableData.indeterminate = listOfEnabledData.some(({id}) => this.tableData.setOfCheckedId.has(id)) && !this.tableData.checked;
  }

  onItemChecked(id: number, checked: boolean): void {
    console.log(id, checked);
    this.updateCheckedSetWaitCheck(id, checked);
    this.refreshCheckedStatusWaitCheck();
  }

  updateCheckedSetWaitCheck(id: number, checked: boolean): void {
    if (checked) {
      this.tableData.setOfCheckedId.add(id);
    } else {
      this.tableData.setOfCheckedId.delete(id);
    }
  }


  showEdit(data: any) {
    this.expressModal = {
      visible: true,
      address: `${data.consignee} ${data.tel}-${data.area}${data.address}`,
      id: data.id,
      expressCode: data.expressCode,
      expressNum: data.expressNum,
    };
  }

  hideExpressModal() {
    this.expressModal = {
      visible: false,
      id: '',
      address: '',
      expressCode: '',
      expressNum: '',
    };
  }

  saveExpressModal() {
    this.operateService.editExpress({
      id: this.expressModal.id,
      expressNum: this.expressModal.expressNum,
      expressCode: this.expressModal.expressCode,
      expressName: this.logistics.filter(i => i.content === this.expressModal.expressCode)[0].name,
    }).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.hideExpressModal();
        this.getExchangeRecordsList();
      }
    });
  }

  export() {
    this.nzModalService.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的订单数据，为了导出速度请尽可能控制时间范围。确定导出？',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        const params = {
          user: this.query.user,
          orderNum: this.query.orderNum,
          goodsType: this.query.goodsType || '',
          state: this.query.state,
          beginTime: this.datePipe.transform(this.query.time[0], 'yyyy-MM-dd') || '',
          endTime: this.datePipe.transform(this.query.time[1], 'yyyy-MM-dd') || '',
          grantBeginTime: this.datePipe.transform(this.query.grantTime[0], 'yyyy-MM-dd') || '',
          grantEndTime: this.datePipe.transform(this.query.grantTime[1], 'yyyy-MM-dd') || '',
        };
        this.operateService.exportExchangeRecords(params)
          .then((res: any) => {
            const name = decodeURI(res.headers.get('content-disposition').replace('attachment; filename=', ''));
            if (res.body.type === 'application/octet-stream') {
              const blob = new Blob([res.body], {type: 'application/vnd.ms-excel'});
              const objectUrl = URL.createObjectURL(blob);
              const a = document.createElement('a');
              a.href = objectUrl;
              a.download = name;
              a.target = '_blank';
              a.click();
              URL.revokeObjectURL(a.href);
              a.remove();
            } else {
              this.nzMessageService.error('导出失败');
            }
          });
      },
      nzCancelText: '关闭'
    });
  }
}
